//
//  JJBigEmojiListView.swift
//  swiftProject
//
//  Created by yangjian on 2021/12/20.
//

//https://www.jianshu.com/p/b60a06bdb375
//https://www.jianshu.com/p/b60a06bdb375        gif swift版本
import UIKit
import HyphenateChat


class JJBigEmojiListView: UIView {

    
    let showGifBackgroundView = UIView.init(frame: CGRect.zero)
    let showGifImageView = UIImageView.init(frame: CGRect.zero)
    var currentShowIndex = 0
    
    
    static let showGifSize = CGSize(width: 80, height: 80)
    
    var name = ""
    var models = [JJBigEmojiModel].init()
    var collectionView : UICollectionView!
    required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.config()
    }
    
    func config(){
        
        //===========showView=============
        
        showGifBackgroundView.backgroundColor = UIColor.white
        showGifBackgroundView.layer.cornerRadius = 6
        showGifBackgroundView.layer.masksToBounds = true
        let edge :CGFloat = 16
        showGifBackgroundView.addSubview(self.showGifImageView)
        self.showGifImageView.snp.makeConstraints { make in
            make.edges.equalTo(UIEdgeInsets(top: edge, left: edge, bottom: edge, right: edge))
            make.size.equalTo(JJBigEmojiListView.showGifSize)
        }
                
        
        //==============collectionView==========
        let layout = UICollectionViewFlowLayout.init()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let emojiWidth = JJBigEmojiListCell.imageViewSize.width + 8
        let lineCount = Int(screen_width() / emojiWidth)
        let leadingOrTranling = (screen_width() - emojiWidth * CGFloat(lineCount)) / 2
        layout.sectionInset = UIEdgeInsets(top: 0, left: leadingOrTranling, bottom: 0, right: leadingOrTranling)
        layout.itemSize = CGSize(width: emojiWidth, height: emojiWidth)
        
        self.collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        
        self.collectionView.backgroundColor = UIColor.clear
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(JJBigEmojiListCell.classForCoder(), forCellWithReuseIdentifier: "JJBigEmojiListCell")
        self.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { make in
            make.top.equalTo(self)
            make.left.equalTo(self)
            make.bottom.equalTo(self)
            make.right.equalTo(self)
        }
        
        let longPressGesture = UILongPressGestureRecognizer.init(target: self, action: #selector(longPressGestureClick(sender: )))
        longPressGesture.minimumPressDuration = 1
        self.collectionView.addGestureRecognizer(longPressGesture)
    }
}

extension JJBigEmojiListView : UICollectionViewDelegate,UICollectionViewDataSource{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        self.models.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "JJBigEmojiListCell", for: indexPath) as! JJBigEmojiListCell
        cell.bindModel(model: self.models[indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let emojiBody = JJMessageBigEmojiBody.init()
        emojiBody.isGif = true;
        emojiBody.topicid = "兔斯基"
        emojiBody.name = self.models[indexPath.row].emojiName;
//        guard let helper = IMChatVCManager.shared().currentChatViewController?.helper else {return }
//        let message : EMChatMessage = EMChatMessage.init(conversationID: conversation.conversationId,
//                                               from: EMClient.shared().currentUsername!,
//                                               to: helper.conversation.conversationId,
//                                               body: emojiBody.covertCustomMessageBody(),
//                                               ext: [:])
//        JJChatService.shared()
//            .sendMessage(message: message)
//        { p in
//        } completion: { result, error in
//        }
    }
}

extension JJBigEmojiListView {
    @objc
    func longPressGestureClick(sender:UILongPressGestureRecognizer) {
        let touchPoint = sender.location(in: self.collectionView)

        switch sender.state {
        case .began:
            let indexPath = self.collectionView.indexPathForItem(at: touchPoint)
            guard let indexPath = indexPath else {
                self.hideGif()
                return
            }
            self.showGif(indexPath: indexPath)
            break
        case .changed:
            let indexPath = self.collectionView.indexPathForItem(at: touchPoint)
            guard let indexPath = indexPath else {
                self.hideGif()
                return
            }
            self.showGif(indexPath: indexPath)
            break
        case .ended:
            self.hideGif()
            break
        default:
            self.hideGif()
            break
//        @unknown default:
//            self.hideGif()
//            break
        }
    }
    
    func showGif(indexPath:IndexPath){
        if self.showGifBackgroundView.superview != nil {
            if self.currentShowIndex == indexPath.row {
                return
            }
        }
        application_keyWindow()?.addSubview(self.showGifBackgroundView)
        self.currentShowIndex = indexPath.row
        self.showGifImageView.setGifImage(data:  self.models[self.currentShowIndex].emojiData)
        guard let item = self.collectionView.cellForItem(at: indexPath) else{
            return
        }
        self.showGifBackgroundView.snp.remakeConstraints { make in
            make.centerX.equalTo(item)
            make.bottom.equalTo(item.snp.top).offset(-12)
        }

        
        
    }
    func hideGif(){
        self.showGifImageView.image = nil
        if self.showGifBackgroundView.superview == nil {
            return
        }
        self.showGifBackgroundView.removeFromSuperview()
        self.currentShowIndex = -1
    }
    
}
